package client;

import factory.MyFactory;
import log.LogService;
import log.LogServiceImpl;
import sun.rmi.runtime.Log;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户端配置类
 */
public class ClientConfig {

    private Socket socket;

    private final String EXIT_SIGNAL = "exit";

    private LogService log = MyFactory.createLogService();


    public ClientConfig() {
        try {
            log.ok("客户端开始连接服务端");
            socket = new Socket("127.0.0.1", 8094);
            log.ok("客户端成功连接服务端");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 启动方法
    public void start() {
        try {

            // 多线程接收服务端的消息
            ServerHandlerImpl serverHandler = new ServerHandlerImpl();
            MyFactory factory = new MyFactory();
            Thread t = factory.createThread(serverHandler);
            t.setDaemon(true); // 设置守护线程，如果客户端线程结束运行，则不需要再从服务端接收消息
            t.start();

            OutputStream outputStream = socket.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
            PrintWriter printWriter = new PrintWriter(bufferedWriter, true);

            Scanner scanner = new Scanner(System.in);
            System.out.println("您可以开始聊天了");
            while (true) {
                String lineMessage = scanner.nextLine();
                if (EXIT_SIGNAL.equals(lineMessage)) {
                    System.out.println("您已退出");
                    break;
                }
                printWriter.println(lineMessage);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接，实际上执行挥手操作
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 接收服务端的消息
     */
    private class ServerHandlerImpl implements Runnable {
        @Override
        public void run() {
            try {
                InputStream inputStream = socket.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                String serverMessage;
                while ((serverMessage = bufferedReader.readLine()) != null) {
                    System.out.println(serverMessage);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
